package org.gpp.proj1.logic.shop;

import java.util.Map;

import org.gpp.proj1.logic.metadata.PartCategory;
import org.gpp.proj1.logic.metadata.PartEntry;
import org.gpp.proj1.logic.profile.PlayerProfile;
import org.gpp.proj1.logic.profile.UnsufficientFundsException;

/**
 * @author Paolo Victor, paolovictor@gmail.com
 */
public class PartShop {
	
	private final PlayerProfile customer;
	private Map<PartCategory, Map<String, PartEntry>> parts;

	public PartShop( Map<PartCategory, Map<String, PartEntry>> parts, PlayerProfile customer ) {
		this.customer = customer;
		this.parts = parts;
	}
	
	public synchronized void buyPart( PartCategory partCategory, String partName, int quantity ) throws UnsufficientFundsException {
		if( partCategory == null || ! parts.containsKey( partCategory ) ) {
			throw new IllegalArgumentException( "Invalid category: \"" + partCategory + "\"" );
		}
		if( partName == null || ! parts.get( partCategory ).containsKey( partName ) ) {
			throw new IllegalArgumentException( "Invalid part: \"" + partName + "\"" );
		}
		
		PartEntry partEntry = parts.get( partCategory ).get( partName );
		
		// Race conditions anyone?
		customer.debit( partEntry.getPrice() * quantity );
		for( int k = 0; k < quantity; k++ ) {
			customer.addPart( partCategory, partEntry );
		}
	}
	
	public Map<PartCategory, Map<String, PartEntry>> getPartMap() {
		return parts;
	}
}
